<?php
use \Tuanduimao\Loader\App as App;
use \Tuanduimao\Utils as Utils;
use \Tuanduimao\Tuan as Tuan;
use \Tuanduimao\Excp as Excp;
use \Tuanduimao\Conf as Conf;
use \Tuanduimao\Wechat as Wechat;


class H5Controller extends \Tuanduimao\Loader\Controller {
	
	function __construct() {
	}


	/**
	 * 用户注册页面
	 * @return [type] [description]
	 */
	function signup() {

		$data['_TITLE'] = '会员申请';
		App::render($data,'h5','pages/signup');
	}


	/**
	 * 用户保存页面
	 */
	function dosignup() {

		// 暂存用户数据
		$_SESSION['name'] = !empty($_POST['name']) ? trim($_POST['name']) : '';
		$_SESSION['mobile'] = !empty($_POST['mobile']) ? trim($_POST['mobile']) : '';

		// 转向微信登录页面
		$we = new Wechat([
			'appid' => $GLOBALS['_C']['appid'],
			'secret' => $GLOBALS['_C']['secret']
		]);

		$url = $we->authUrl(  App::PR('h5','authback') );

		// 转向授权页面
		header('HTTP/1.1 301 Moved Permanently');
		header('Location: ' .  $url );
	}


	/**
	 * 授权登录完毕，读取用户信息
	 * @return [type] [description]
	 */
	function authback() {

		$we = new Wechat([
			'appid' => $GLOBALS['_C']['appid'],
			'secret' => $GLOBALS['_C']['secret']
		]);

		$userInfo = $we->getAuthUser($_GET['code'], $_GET['state']);
		if ( !empty($_SESSION['name']) ) {
			$userInfo['name'] = $_SESSION['name'];
		}
		if ( !empty($_SESSION['mobile']) ) {
			$userInfo['mobile'] = $_SESSION['mobile'];
		}

		$userInfo['nickName'] = $userInfo['nickname'];
		$userInfo['avatarUrl'] = $userInfo['headimgurl'];

		// 数据入库
		$prefix = !empty($_GET['prefix']) ? trim($_GET['prefix']) : $GLOBALS['_C']['prefix'];
		$table = !empty($_GET['table']) ? trim($_GET['table']) : $GLOBALS['_C']['user.table']; 
		$u = App::M('User',  ['prefix'=>$prefix, 'name'=>$table] );

		$user = $u->getLine("WHERE mobile=? LIMIT 1", [], [$userInfo['mobile']]);
		if ( $user == null ) {
			$user= $u->getLine("WHERE openid=? LIMIT 1", [], [$userInfo['openid']]);
		}

		if ( $user == null ) {
			$userInfo['cid'] = Utils::genNum(7);
			$user = $u->create( $userInfo );
			$userInfo = $user;
		}

		$userInfo['_user'] = $user['_id'];
		$userInfo['_group'] = 'member';
		$user = $u->update( $user['_id'],  $userInfo );

		$this->success( $user['cid'] );
	}


	/**
	 * 转向成功页
	 */
	private function success( $cid = '8888888') {
		$data['_TITLE'] = '申请成功';
		$data['cid']  = $cid;
		App::render($data,'h5','pages/success');
	}

}